﻿<%@ WebHandler Language="C#" Class="UserLogin" %>

using System;
using System.IO;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Collections;
using ReportBusiness;

/*
 * Description: 
 * Copyright (c) : 通力凯顿（北京）系统集成有限公司
 * Writer:zhunan
 * Date:2023.4.21
 */

public class UserLogin : IHttpHandler
{
    public class PageObjectTree
    {
        //全局变量用于保存数据
        private List<PageObjectTree> treeNode = new List<PageObjectTree>();
        public string label { get; set; }
        public string id { get; set; }
        public string pageurl { get; set; }
        public string isnew { get; set; }
        public string pagetype { get; set; }
        public string factoryid { get; set; }
        public string ip { get; set; }

        public IList<PageObjectTree> children = new List<PageObjectTree>();
        //递归生成树
        public List<PageObjectTree> BindTree(DataTable dtSource, PageObjectTree parentNode, string parentID)
        {
            DataRow[] rows = dtSource.Select(string.Format("parentid = '{0}'", parentID));
            foreach (DataRow row in rows)
            {
                PageObjectTree tree = new PageObjectTree();
                tree.label = row["label"].ToString();
                tree.id = row["id"].ToString();
                tree.pageurl = row["pageurl"].ToString();
                tree.isnew = row["isnew"].ToString();
                tree.pagetype = row["pagetype"].ToString();
                tree.factoryid = row["factoryid"].ToString();
                tree.ip = row["ip"].ToString();

                //递归
                BindTree(dtSource, tree, row["id"].ToString());

                if (parentNode == null)
                {
                    treeNode.Add(tree);
                }
                else
                {
                    parentNode.children.Add(tree);
                }
            }
            return treeNode;
        }
    }

    uMESReportOracleDAL dal = new uMESReportOracleDAL();
    PageObjectTree t = new PageObjectTree();
    List<PageObjectTree> treeNodes = new List<PageObjectTree>();
    string IP = System.Configuration.ConfigurationManager.AppSettings["IP"];
    ADHelper help = new ADHelper();
    public bool IsReusable { get { return false; } }
    public void ProcessRequest(HttpContext context)
    {
        string requestjson = "";
        using (StreamReader reader = new StreamReader(context.Request.InputStream)) { requestjson = reader.ReadToEnd(); }
        JObject jObject = JsonConvert.DeserializeObject(requestjson) as JObject;
        if (jObject["type"] != null)
        {
            try
            {
                Result r = new Result();
                context.Response.ContentType = "text/json";
                string type = jObject["type"].ToString();
                switch (type)
                {
                    case "getUserReportPages":
                        r = getUserReportPages(jObject);//查询用户配置报表
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "isUserExists":
                        r = isUserExists(jObject);//查询用户是否存在
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "login":
                        r = login(jObject);//登录
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    default:
                        break;
                }
            }
            catch (Exception e)
            {
                Result r = new Result();
                r.data = null;
                r.meta = new Result.Meta(500, e.Message);
                r.total = 0;
                context.Response.ContentType = "text/json";
                context.Response.Write(JsonConvert.SerializeObject(r));
            }
        }
    }

    //查询用户配置报表
    Result getUserReportPages(JObject jObject)
    {
        string sql = @"
SELECT '1' ID,'报表系统' LABEL, '0' parentid,NULL pageurl,NULL isnew,NULL pagetype,NULL factoryid
FROM (
    SELECT t.pageid,t.pagename,t.pagetype,f.factoryname,decode(t.isnew,1,'new','') isnew
    FROM mes_employeereportpage mt
    INNER JOIN mes_reportpage t ON mt.pageid = t.pageid
    INNER JOIN employee e ON e.employeeid = mt.employeeid
    LEFT JOIN factory f ON f.factoryid = t.factoryid
    WHERE t.status = 1 AND mt.employeeid = '{0}'
) t
HAVING COUNT(t.pageid) > 0

UNION ALL
SELECT '2' ID,'看板' LABEL, '1' parentid,NULL pageurl,NULL isnew,NULL pagetype,NULL factoryid
FROM (
    SELECT t.pageid,t.pagename,t.pagetype,f.factoryname,decode(t.isnew,1,'new','') isnew
    FROM mes_employeereportpage mt
    INNER JOIN mes_reportpage t ON mt.pageid = t.pageid
    INNER JOIN employee e ON e.employeeid = mt.employeeid
    LEFT JOIN factory f ON f.factoryid = t.factoryid
    WHERE t.status = 1 AND mt.employeeid = '{0}' AND t.pagetype = '看板'
) t
HAVING COUNT(t.pageid) > 0

UNION ALL
SELECT '3' ID,'报表' LABEL, '1' parentid,NULL pageurl,NULL isnew,NULL pagetype,NULL factoryid
FROM (
    SELECT t.pageid,t.pagename,t.pagetype,f.factoryname,decode(t.isnew,1,'new','') isnew
    FROM mes_employeereportpage mt
    INNER JOIN mes_reportpage t ON mt.pageid = t.pageid
    INNER JOIN employee e ON e.employeeid = mt.employeeid
    LEFT JOIN factory f ON f.factoryid = t.factoryid
    WHERE t.status = 1 AND mt.employeeid = '{0}' AND t.pagetype = '报表'
) t
HAVING COUNT(t.pageid) > 0

UNION ALL
SELECT t.factoryname || '看板' id,t.factoryname || '看板' LABEL, '2' parentid,NULL pageurl,NULL isnew,NULL pagetype,NULL factoryid
FROM (
  SELECT t.pageid,t.pagename,t.pagetype,f.factoryname,decode(t.isnew,1,'new','') isnew
  FROM mes_employeereportpage mt
  INNER JOIN mes_reportpage t ON mt.pageid = t.pageid
  INNER JOIN employee e ON e.employeeid = mt.employeeid
  LEFT JOIN factory f ON f.factoryid = t.factoryid
  WHERE t.status = 1 AND mt.employeeid = '{0}' AND t.pagetype = '看板' AND f.factoryname IS NOT NULL
) t
GROUP BY t.factoryname

UNION ALL
SELECT t.pageid ID,t.pagename LABEL,'2' parentid,t.pageurl,t.isnew,t.pagetype,t.factoryid
FROM mes_employeereportpage mt
INNER JOIN mes_reportpage t ON mt.pageid = t.pageid
INNER JOIN employee e ON e.employeeid = mt.employeeid
LEFT JOIN factory f ON f.factoryid = t.factoryid
WHERE t.status = 1 AND mt.employeeid = '{0}' AND t.pagetype = '看板' AND t.factoryid IS NULL

UNION ALL
SELECT t.pageid ID,t.pagename LABEL,f.factoryname || '看板' parentid,t.pageurl,t.isnew,t.pagetype,t.factoryid
FROM mes_employeereportpage mt
INNER JOIN mes_reportpage t ON mt.pageid = t.pageid
INNER JOIN employee e ON e.employeeid = mt.employeeid
LEFT JOIN factory f ON f.factoryid = t.factoryid
WHERE t.status = 1 AND mt.employeeid = '{0}' AND t.pagetype = '看板' AND f.factoryname IS NOT NULL

UNION ALL
SELECT t.factoryname || '报表' id,t.factoryname || '报表' LABEL, '3' parentid,NULL pageurl,NULL isnew,NULL pagetype,NULL factoryid
FROM (
  SELECT t.pageid,t.pagename,t.pagetype,f.factoryname,decode(t.isnew,1,'new','') isnew
  FROM mes_employeereportpage mt
  INNER JOIN mes_reportpage t ON mt.pageid = t.pageid
  INNER JOIN employee e ON e.employeeid = mt.employeeid
  LEFT JOIN factory f ON f.factoryid = t.factoryid
  WHERE t.status = 1 AND mt.employeeid = '{0}' AND t.pagetype = '报表' AND f.factoryname IS NOT NULL
) t
GROUP BY t.factoryname

UNION ALL
SELECT t.pageid ID,t.pagename LABEL,'3' parentid,t.pageurl,t.isnew,t.pagetype,t.factoryid
FROM mes_employeereportpage mt
INNER JOIN mes_reportpage t ON mt.pageid = t.pageid
INNER JOIN employee e ON e.employeeid = mt.employeeid
LEFT JOIN factory f ON f.factoryid = t.factoryid
WHERE t.status = 1 AND mt.employeeid = '{0}' AND t.pagetype = '报表' AND t.factoryid IS NULL

UNION ALL
SELECT t.pageid ID,t.pagename LABEL,f.factoryname || '报表' parentid,t.pageurl,t.isnew,t.pagetype,t.factoryid
FROM mes_employeereportpage mt
INNER JOIN mes_reportpage t ON mt.pageid = t.pageid
INNER JOIN employee e ON e.employeeid = mt.employeeid
LEFT JOIN factory f ON f.factoryid = t.factoryid
WHERE t.status = 1 AND mt.employeeid = '{0}' AND t.pagetype = '报表' AND f.factoryname IS NOT NULL";
        sql = string.Format(sql, jObject["employeeid"].ToString());
        DataTable dt = dal.GetDataTable(sql);
        dt.Columns.Add("ip");
        foreach (DataRow dr in dt.Rows)
        {
            dr["ip"] = IP;
        }
        foreach (DataColumn col in dt.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        Result r = new Result();
        treeNodes = t.BindTree(dt, null, "0");
        r.data = treeNodes;
        r.total = Convert.ToInt32(0);
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }

    //登录
    Result login(JObject jObject)
    {
        string sql = "SELECT e.employeename,e.employeeid,e.password,'{1}' host FROM employee e WHERE lower(e.employeename) = '{0}'";
        sql = string.Format(sql, jObject["employeename"].ToString().ToLower(), IP);
        DataTable dt = dal.GetDataTable(sql);
        foreach (DataColumn col in dt.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        Result r = new Result();
        if (dt.Rows.Count == 0)
        {
            r.data = null;
            r.total = Convert.ToInt32(0);
            r.meta = new Result.Meta(200, "用户不存在");
        }
        else
        {
            string password = EncryptAndDecryptTool.DesDecrypt(jObject["password"].ToString());
            string pwd = dt.Rows[0]["password"].ToString();
            if ((pwd == password) || (help.Decrypto(pwd) == password))
            {
                r.data = dt;
                r.total = Convert.ToInt32(1);
                r.meta = new Result.Meta(200, "登录成功");
            }
            else
            {
                r.data = null;
                r.total = Convert.ToInt32(0);
                r.meta = new Result.Meta(200, "密码不正确");
            }
        }
        return r;
    }

    //用户是否存在
    Result isUserExists(JObject jObject)
    {
        string sql = "SELECT e.employeename,e.employeeid,'{1}' host FROM employee e WHERE e.employeename = '{0}'";
        sql = string.Format(sql, jObject["employeename"].ToString(), IP);
        DataTable dt = dal.GetDataTable(sql);
        foreach (DataColumn col in dt.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        Result r = new Result();
        r.data = dt;
        r.total = Convert.ToInt32(dt.Rows.Count);
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }
}